<template>
  <a-spin :spinning="loading">
    <!-- 没有价格信息时，先显示服务选择器 -->
    <div v-if="!priceInfo" class="service-type">
      <div class="tips">初次使用，请选择报价项</div>
      <service-type-selector ref="serviceTypeSelectorRef" :currencyId="apply.raw.value.clientInfo.currencyID" />
      <a-divider />
      <div class="buttons">
        <a-space size="middle">
          <a-button type="primary" :loading="saveServiceTypeLoading" @click="handleServiceTypesSave">Save</a-button>
        </a-space>
      </div>
    </div>
    <!-- 价格编辑器 -->
    <div v-else>
      <div class="operations" :class="{ readonly: readonly }">
        <a-space>
          <a-button v-if="!readonly" type="link" size="small" @click="handleClickAddLanguagePair">
            <a-space>
              <e-icon type="LanguagePair" />
              Add Language Pair
            </a-space>
          </a-button>
          <a-button v-if="!readonly" type="link" size="small" @click="handleClickEditServiceTypes">
            <a-space>
              <e-icon type="add" />
              Edit Service Types
            </a-space>
          </a-button>
          <a-button
            v-if="!readonly"
            type="link"
            size="small"
            :loading="saveLoading"
            @click="handleSaveServicePrice(false)">
            <a-space>
              <e-icon type="save" />
              Save
            </a-space>
          </a-button>
        </a-space>
        <a-button type="text" size="small" @click="handleExportQuota">
          <a-space>
            <e-icon type="excel" font-size="16px" line-height="22px" default-color />
            Export Service Price
          </a-space>
        </a-button>
      </div>
      <div class="table">
        <a-row>
          <a-col :span="4" class="cell field">Applicant</a-col>
          <a-col :span="8" class="cell value">{{ apply.raw.value.displayName }}</a-col>
          <a-col :span="4" class="cell field">Status</a-col>
          <a-col :span="8" class="cell value">{{ apply.raw.value.statusName }}</a-col>
        </a-row>
        <a-row>
          <a-col :span="4" class="cell field">Attachment (Price Sheet)</a-col>
          <a-col :span="20" class="cell value">
            <a-tag
              v-if="apply.raw.value.attchName"
              class="attachment-tag"
              @click="handleDownload(apply.raw.value.attchName, apply.raw.value.attchPath)">
              <a-space><e-icon type="Document" />{{ apply.raw.value.attchName }}</a-space>
            </a-tag>
          </a-col>
        </a-row>
      </div>
      <price-editor
        ref="priceEditorRef"
        :price-info="priceInfo"
        :pin-height="0"
        :readonly="readonly"
        :reviewing="reviewing"
        @delete-language-pair="handleDeleteLanguagePair" />
    </div>
    <a-modal
      v-model:visible="showLanguagePairsModal"
      width="888px"
      title="Add Language Pair"
      wrap-class-name="primary-modal"
      ok-text="Add"
      @cancel="showLanguagePairsModal = false"
      @ok="handleAddLanguagePair">
      <a-form layout="vertical">
        <a-form-item label="Language Pair" name="langPairID">
          <a-select v-model:value="willAddedLanguagePairs" mode="multiple" option-filter-prop="label">
            <a-select-option
              v-for="item in availableLanguagePairs"
              :key="item.langPairID"
              :label="item.langPairName"
              :disabled="languagePairs.find(language => language.langPairID === item.langPairID)">
              {{ item.langPairName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="showServiceTypeModal"
      width="888px"
      title="Edit Service Types"
      wrap-class-name="primary-modal"
      :destroy-on-close="true"
      @cancel="showServiceTypeModal = false"
      @ok="handleServiceTypesUpdate">
      <service-type-selector
        ref="serviceTypeSelectorModalRef"
        :price-info="priceInfo"
        :currencyId="apply.raw.value.clientInfo.currencyID" />
    </a-modal>
  </a-spin>
</template>

<script setup>
import { ref, inject, computed } from 'vue'
import EIcon from '@/components/EIcon.vue'
import ServiceTypeSelector from './ServiceTypeSelector.vue'
import PriceEditor from '@/pages/Client/servicePrice/components/PriceEditor.vue'
import ServicePrice from '@/api/client/servicePrice.js'
import {
  SELECT_SERVICE_TYPE,
  SERVICE_TYPE_NO_CHANGE,
  SERVICE_TYPE_UPDATED,
  PRICE_SAVED,
  LANGUAGE_PAIR_ADDED,
  LANGUAGE_PAIR_DELETED,
  PRICE_AUTO_SAVED
} from '@/constants/message.js'
import useDownload from '@/hooks/useDownload.js'
import Config from '@/config'
import Util from '@/utils'
const downloadHandler = useDownload
const { message } = inject('Feedback')
const priceEditorRef = ref(null)
const props = defineProps({
  apply: {
    type: Object,
    default() {
      return {
        raw: ref({ clientInfo: {} }),
        transformed: ref({ clientQuoteApplyCBG: {}, getClientQuoteApplyCBGDemandTypes: [] })
      }
    }
  },
  availableLanguagePairs: {
    type: Array,
    default() {
      return []
    }
  },
  readonly: {
    type: Boolean,
    default: false
  },
  reviewing: {
    type: Boolean,
    default: false
  }
})
// 语言对弹窗
const showLanguagePairsModal = ref(false)
// 服务项弹窗
const showServiceTypeModal = ref(false)
// 要添加的语言对
const willAddedLanguagePairs = ref([])
// 现在使用的语言对信息
const languagePairs = computed(() => props.apply.raw.value.langPair)
// 价格信息
const priceInfo = computed(() => props.apply.raw.value.clientQuoteApplyServicePrice)
const loading = ref(false)
const saveLoading = ref(false)
const saveServiceTypeLoading = ref(false)
const emits = defineEmits(['loadPrice'])
const loadPrice = () => {
  emits('loadPrice')
}
const serviceTypeSelectorRef = ref(null)
const serviceTypeSelectorModalRef = ref(null)
const handleClickAddLanguagePair = () => {
  willAddedLanguagePairs.value.splice(0)
  showLanguagePairsModal.value = true
  handleSaveServicePrice(true)
}
const handleClickEditServiceTypes = () => {
  showServiceTypeModal.value = true
  handleSaveServicePrice(true)
}
const handleAddLanguagePair = () => {
  loading.value = true
  ServicePrice.addLanguagePairs(props.apply.raw.value.id, willAddedLanguagePairs.value)
    .then(() => {
      message.success(LANGUAGE_PAIR_ADDED)
      loadPrice()
      showLanguagePairsModal.value = false
    })
    .finally(() => {
      loading.value = false
    })
}
const handleDeleteLanguagePair = (sLang, tLang) => {
  handleSaveServicePrice(true).then(() => {
    loading.value = true
    ServicePrice.deleteLanguagePairs(props.apply.raw.value.id, sLang, tLang)
      .then(() => {
        message.success(LANGUAGE_PAIR_DELETED)
        loadPrice()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const handleServiceTypesSave = () => {
  const serviceTypes = serviceTypeSelectorRef.value.getCheckedItem()
  if (!serviceTypes || serviceTypes.length === 0) {
    message.warning(SELECT_SERVICE_TYPE)
  } else {
    saveServiceTypeLoading.value = true
    ServicePrice.saveServiceTypes(props.apply.raw.value.id, serviceTypes)
      .then(() => {
        loadPrice()
      })
      .finally(() => {
        saveServiceTypeLoading.value = false
      })
  }
}
const handleDownload = (name, path) => {
  downloadHandler.showDownload([
    {
      ServerFileID: 2,
      Url: Config.SIGNAL_R_URL,
      RealPath: path.replace('/\\/g', '\\\\'),
      FullName: `\\${name}`
    }
  ])
}
const handleServiceTypesUpdate = () => {
  const serviceTypes = serviceTypeSelectorModalRef.value.getCheckedItem()
  if (!serviceTypes) {
    message.error(SELECT_SERVICE_TYPE)
  } else {
    if (serviceTypes.length === 0) {
      message.error(SERVICE_TYPE_NO_CHANGE)
    } else {
      ServicePrice.saveServiceTypes(props.apply.raw.value.id, serviceTypes).then(() => {
        message.success(SERVICE_TYPE_UPDATED)
        loadPrice()
        showServiceTypeModal.value = false
      })
    }
  }
}
const handleExportQuota = () => {
  ServicePrice.exportQuota(props.apply.raw.value.id).then(res => {
    Util.downloadBlob(res, 'Service-Price.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  })
}
const handleSaveServicePrice = (passive = false) => {
  saveLoading.value = true
  const postData = priceEditorRef.value.priceInfoCopy.map(item => {
    const { sLang, tLang, serviceType, fileKind, breakDown, clientPrice } = item
    return {
      sLang,
      tLang,
      serviceType,
      fileKind,
      breakDown,
      clientPrice: parseFloat(clientPrice),
      apply: props.apply.raw.value.id,
      unit: item.workloadUnit,
      currency: props.apply.raw.value.clientInfo.currencyID
    }
  })
  return new Promise(resolve => {
    ServicePrice.savePrice(postData)
      .then(() => {
        passive ? message.success(PRICE_AUTO_SAVED) : message.success(PRICE_SAVED)
        resolve()
      })
      .finally(() => {
        saveLoading.value = false
      })
  })
}
defineExpose({ handleSaveServicePrice })
</script>

<style lang="less" scoped>
.service-type {
  padding: 0 300px;
  .tips {
    color: @text-black;
    padding-bottom: 16px;
  }
  .buttons {
    text-align: center;
  }
}
.operations {
  display: flex;
  justify-content: space-between;
  &.readonly {
    justify-content: right;
  }
}
@border: 1px solid @lighter-gray;
.table {
  border: @border;
  margin: 24px 0;
  .cell {
    padding: 10px 14px;
    border-bottom: @border;
    border-right: @border;
    &:last-child {
      border-right: none;
    }
    &.field {
      background-color: @milk;
      color: @text-gray;
    }
    .ant-tag {
      background-color: @phase-default;
      border: none;
      padding: 1px 12px;
      font-size: 14px;
      &.contact-tag {
        color: @black;
      }
      &.attachment-tag {
        color: @primary-color;
        cursor: pointer;
        user-select: none;
        .e-icon {
          color: @text-gray !important;
        }
      }
    }
  }
  .ant-row:last-child {
    .cell {
      border-bottom: none;
    }
  }
}
</style>
